const MenuConfig = {
	ITEM_CLASS: 'menu-item',
	ITEM_RIGHT: 'row-center',
	ITEM_NUM: "font-third",
	ITEM_ICON: "img/ic_menu_point.png",
	ITEM_ICON_RIGHT: "img/ic_right.png",
	ITEM_ICON_CLASS: 'icon-small'
}

class Menu {
	constructor(options) {
		this.data = options.data || [];
		this.container = document.querySelector(options.container);
		this.onClickItem = options.onClickItem || function() {};
		this.onSwitchChange = options.onSwitchChange || function() {};
		this.render();
		this.bindEvents();
	}

	render() {
		if (this.data.length == 0) return;
		this.container.innerHTML = '';
		const html = this.data.map((item, index) =>
			this.generateTabItem(item, index)
		).join('');
		this.container.innerHTML = html;
	}

	generateTabItem(e, index) {
		let rightItem = `<div class="${MenuConfig.ITEM_RIGHT}">
						<span class="${MenuConfig.ITEM_NUM}">${e.value}</span>
						<img src="${getRootPath() + MenuConfig.ITEM_ICON_RIGHT}" class="${MenuConfig.ITEM_ICON_CLASS}" />
					</div>`;
		if (e.type && e.type == 'switch') {
			let value = e.value;
			const switchChecked = e.value == '1' ? 'checked' : '';
			rightItem = `<label class="toggle-switch">
						<input type="checkbox" class="toggle-input" ${switchChecked}>
						<span class="toggle-slider"></span>
					</label>`
		}

		return `<div class="${MenuConfig.ITEM_CLASS}" data-item='${escapeHtml(JSON.stringify(e))}'>
					<img src="${getRootPath() + e.icon}" class="${MenuConfig.ITEM_ICON_CLASS}" />
					<span class="label">${e.label}</span>
					${rightItem}
				</div>`;
	}

	bindEvents() {
		this.container.addEventListener('click', e => {
			// 检查点击目标是否是switch相关元素
			const itemElement = e.target.closest(`.${MenuConfig.ITEM_CLASS}`);
			const target = e.target;
			const parent = target.parentNode;
			if (parent.classList.contains('toggle-switch')) {
				e.stopPropagation(); 
				return
			} 
			if (itemElement) {
				try {
					const itemData = JSON.parse(itemElement.dataset.item);
					this.onClickItem(itemData);
				} catch (error) {
					console.error('解析item数据失败:', error);
				}
			}
		})
		// 为switch添加单独的事件处理
		this.container.addEventListener('change', e => {
			if (e.target.classList.contains('toggle-input')) {
				const switchElement = e.target;
				const itemElement = switchElement.closest(`.${MenuConfig.ITEM_CLASS}`);
				if (itemElement) {
					try {
						const itemData = JSON.parse(itemElement.dataset.item);
						// 更新数据中的value值
						itemData.value = switchElement.checked ? '1' : '0';
						// 可以在这里触发switch变化的自定义事件
						this.onSwitchChange(itemData, switchElement.checked);
					} catch (error) {
						console.error('解析item数据失败:', error);
					}
				}
			}
		});
	}

	update(newData) {
		this.data = newData;
		this.render();
	}
}
